package cn.buk.qms.task;

import cn.buk.qms.service.BillService;
import cn.buk.tms.bill.service.BillCheckService;
import cn.buk.tms.flight.service.AutoTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时任务
 *
 * @author yfdai
 */
@Profile({"prod"})
@Component
public class SecondaryTask {

  private static final int SERVER_SECONDARY = 2;

  /**
   * 当前应用所在服务器的id
   */
  private final int serverId;

  /**
   * 当前应用所属的拥有者在数据库中对应的企业id
   */
  private final int ownerId;

  private String getAgentName() {
    return "system-" + serverId;
  }

  private final BillService billService;
  private final BillCheckService billCheckService;
  private final AutoTicketService autoTicketService;

  @Autowired
  public SecondaryTask(@Value("${server_id}") int serverId,
                       @Value("${owner_enterprise_id}") int ownerId,
                       BillService billService,
                       BillCheckService billCheckService,
                       AutoTicketService autoTicketService) {
    this.serverId = serverId;
    this.ownerId = ownerId;

    this.billService = billService;
    this.billCheckService = billCheckService;
    this.autoTicketService = autoTicketService;

  }

  @Async
  @Scheduled(cron = "0 0/5 22,23 * * *")
  public void updateBillRefundTicketPnrNo() {
    if (serverId != SERVER_SECONDARY) {
      return;
    }
    billService.updateBillRefundTicketPnrNo(getAgentName());
  }

  /**
   * 将线上订单同步到线下订单进行处理
   */
  @Async
  @Scheduled(cron = "0 0/5 * * * *")
  public void autoCheckTrainBillPsgCount() {
    if (serverId != SERVER_SECONDARY) {
      return;
    }

    //自动修改火车票账单中psg_count的数值
    billCheckService.autoCheckTrainBillPsgCount(getAgentName());
  }


  /**
   * 每30秒查找一次需要自动BSP出票的
   */
  @Scheduled(cron = "0/30 * * * * *")
  public void checkAutoPrintTickets() {
    if (serverId != SERVER_SECONDARY) {
      return;
    }

    try {
      autoTicketService.checkAutoTicketOrder(this.ownerId, getAgentName());

      //南航NDC自动退票
//      autoRefundService.checkFlightRefundOrder(this.ownerId, getAgentName());

      //南航NDC自动改签的
//      autoChangeService.checkFlightChangeOrder(this.ownerId, getAgentName());

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
